|
|
|
|
|
|
|
Except for a few differences, working with collections is much the same as working with arrays. An array is a list of variables that are accessed using the same variable name and an index value. Using arrays, you can store many occurrences of data. Each element of an array can be treated by the application code as a standard variable. The difference is the index value that specifies which element in the array to access. One of the restrictions of an array is that all of the elements must contain the data of the same data type. Another restriction is that you must define the array with an exact number of elements before you can access it. You do this using the following line of code: |
|
|
|
|
|
|
|
|
Public Array_Demo(9) As String |
|
|
|
|
|
|
|
|
This will define an array, Array_Demo, that has 10 string elements in it. However, if you do not know the maximum number of elements you might need, you could use the ReDim definition statement to change the number of elements in the array, as shown here: |
|
|
|
|
|
|
|
|
ReDim Preserve Array_Demo(25) |
|
|
|
|
|
|
|
|
You can see that you are not redefining the array itself, just the amount of memory it needs in the application. The Preserve keyword tells Visual Basic not to clear any existing data from the array during the process. Finally, when you define arrays, you can specify the starting value for the array. The default value in Visual Basic is zero, unless you add the Option Base 1 statement to the definitions area of your application. |
|
|
|
|
|
|
|
|
Now that you have taken a quick look at standard arrays, see how a collection works. Collections play an important role in the programming of a Visual Basic application. They are always present and are updated automatically as things change in the application. For example, if you are running an MDI-based application and start more instances of a child form, the Forms collection's Count property is updated by Visual Basic. Besides the predefined collections, you can also define your own. |
|
|
|
|
|
|
|
|
The advantage of using a collection over an array is that collections will add new elements to an application without having to code anything special as with arrays. In addition, a collection can contain almost any combination of objects, although if you are using a collection it will probably be for a specific reason; thus, the objects in it will be of the same type. |
|
|
|
|
|
|
|
|
When you create your own collection, you must manage it yourself. Any collection that you create will be a member of the Collection class as defined by Visual Basic. To define a collection, add the following code at the module level of your application: |
|
|
|
|
|
|
|
|
Public colMyTextInput As New Collection |
|
|
|
|
|